﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using WCYCReader.Models;
using System.Windows.Threading;
using System.Windows.Data;
using WCYCReader.Main;
using System.Windows.Media;
using System.Windows.Input;
using WCYCReader.Utility;
using System.Windows.Media.Animation;
using System.ComponentModel;
using WCYCReader.Main.Core;
using System.Windows.Media.Imaging;
using System.Threading;
using WCYCReader.Drawing;
using WCYCReader.UserControls;
using WCYCReader.Resources;
using System.Windows.Controls.Primitives;
using System.Reflection;
using SurfaceAd.SDK.WP;
using System.Text;


namespace WCYCReader.Pages
{
    public partial class BookReaderPage : PhoneApplicationPage
    {
        private bool canvasClipped;
        private int previousPageCanvasIndex;
        private int currentPageCanvasIndex;
        private int nextPageCanvasIndex;
        private bool loaded;
        private int initPage;
        private int fontSize;
        private Canvas currentCanvas;
        private Canvas nextCanvas;
        private Canvas previousCanvas;
        private Storyboard pageTurnStoryboard;
        private GraphicsExtendedImpl graphics;
        public pageInfo drawPage;
        private Typesetting tp;
        public int BookReader_BackgroundNum;
        public double BookReader_Percentage;
        public bool BookReader_NightMode;
        public string FileName;
        public string BookReader_BookID;
        private int readerIndex;
        private int previousPageIndex;
        private int previousPageCount;
        private int currentPageIndex;
        private int currentPageCount;
        private int nextPageIndex;
        private int nextPageCount;

        private LocalBookProgressList_M lbpl_m = new LocalBookProgressList_M();
        public ReaderPageBrightControl rpbc = new ReaderPageBrightControl();
        public ReaderPageTimesControl rptc = new ReaderPageTimesControl();
        public ReaderPagePercentageControl rppc = new ReaderPagePercentageControl();
        public ReaderPageBackgroundControl rpbgc = new ReaderPageBackgroundControl();
        public ReaderPageTopControl rpTopControl;
        public ReaderPageBottomControl rpBottomControl;
        public PopupContainerControl pcc = new PopupContainerControl();
        public DispatcherTimer UpdateTime = new DispatcherTimer();
        private TextBlock menuText = new TextBlock();//提示文字
        //private TextBlock menuTextResponse = new TextBlock();//显示时间和进度的statusbar
        private TextBlock percentageText = new TextBlock();//进度
        private TextBlock timeText = new TextBlock();//显示当前时间
        private ReaderPageHelp rph;

        private Popup popupReaderConfig = new Popup();

        //广告
        private Popup popupAd = new Popup();
        private SurfaceAdControl sufaceAdControl = null;
        private TextBlock txtAdClickInfo = new TextBlock();//广告支持提示
        private string adPosition = "10f747b604abcf89c926eb7a379750f4", adToken = "Yw4yV2UBYQhjAjJQZRdhCGMQ";


        #region 菜单设置
        void PopupFactory(string userControlName)
        {
            if (popupReaderConfig == null)
            {
                popupReaderConfig = new Popup();
            }
            popupReaderConfig.Height = 120;
            popupReaderConfig.Width = 480;
            StackPanel panel = new StackPanel()
            {
                Background = new SolidColorBrush(Colors.LightGray)
            };

            if ("BrightControl".Equals(userControlName))
                panel.Children.Add(new BrightControl(this));
            else if ("BackgroundControl".Equals(userControlName))
                panel.Children.Add(new BackgroundControl(this));
            else if ("ProgressControl".Equals(userControlName))
                panel.Children.Add(new ProgressControl(this));
            else if ("FontFamilyControl".Equals(userControlName))
                panel.Children.Add(new FontFamilyControl(this));

            popupReaderConfig.Child = panel;
            popupReaderConfig.IsOpen = true;
        }
        private void BuildLocalizedApplicationBar()
        {
            // 将页面的 ApplicationBar 设置为 ApplicationBar 的新实例。
            ApplicationBar = new ApplicationBar();
            ApplicationBar.Mode = ApplicationBarMode.Minimized;

            // 创建新按钮并将文本值设置为 AppResources 中的本地化字符串。
            ApplicationBarIconButton appBarButton1 = new ApplicationBarIconButton()
            {
                IconUri = new Uri("/Resource/Images/bright.png", UriKind.Relative),
                Text = "亮度调节",
            };
            appBarButton1.Click += delegate(object sender, EventArgs e)
            {
                PopupFactory("BrightControl");
            };
            ApplicationBarIconButton appBarButton2 = new ApplicationBarIconButton()
            {
                IconUri = new Uri("/Resource/Images/progress.png", UriKind.Relative),
                Text = "进度跳转",
            };
            appBarButton2.Click += delegate(object sender, EventArgs e)
            {
                PopupFactory("ProgressControl");
            };
            ApplicationBarIconButton appBarButton3 = new ApplicationBarIconButton()
            {
                IconUri = new Uri("/Resource/Images/font.png", UriKind.Relative),
                Text = "字体调整",
            };
            appBarButton3.Click += delegate(object sender, EventArgs e)
            {
                PopupFactory("FontFamilyControl");
            };
            ApplicationBarIconButton appBarButton4 = new ApplicationBarIconButton()
            {
                IconUri = new Uri("/Resource/Images/background.png", UriKind.Relative),
                Text = "背景选择",
            };
            appBarButton4.Click += delegate(object sender, EventArgs e)
            {
                PopupFactory("BackgroundControl");
            };

            ApplicationBar.Buttons.Add(appBarButton1);
            ApplicationBar.Buttons.Add(appBarButton2);
            ApplicationBar.Buttons.Add(appBarButton3);
            ApplicationBar.Buttons.Add(appBarButton4);

            // 使用 AppResources 中的本地化字符串创建新菜单项。
            //ApplicationBarMenuItem appBarMenuItem1 = new ApplicationBarMenuItem() { Text = "正常模式" };
            //appBarMenuItem1.Click += delegate(object sender, EventArgs e)
            //{
            //    bool panelNight = (bool)SettingHelper.GetValueFromSettings("BookReader_NightMode");
            //    appBarButton1.Text = panelNight ? "夜间模式" : "正常模式";
            //    SettingHelper.SaveInToSettings("BookReader_NightMode", !panelNight);
            //    BookReader_NightMenu();
            //};
            ApplicationBarMenuItem appBarMenuItemDark = new ApplicationBarMenuItem() { Text = "夜间模式" };
            ApplicationBarMenuItem appBarMenuItemLight = new ApplicationBarMenuItem() { Text = "正常模式" };
            appBarMenuItemDark.Click += delegate(object sender, EventArgs e)
            {
                SettingHelper.SaveInToSettings("BookReader_NightMode", true);
                BookReader_NightMenu();
                appBarMenuItemDark.IsEnabled = false;
                appBarMenuItemLight.IsEnabled = true;
            };
            appBarMenuItemLight.Click += delegate(object sender, EventArgs e)
            {
                SettingHelper.SaveInToSettings("BookReader_NightMode", false);
                BookReader_NightMenu();
                appBarMenuItemLight.IsEnabled = false;
                appBarMenuItemDark.IsEnabled = true;
            };
            if ((bool)SettingHelper.GetValueFromSettings("BookReader_NightMode"))
                appBarMenuItemDark.IsEnabled = false;
            else
                appBarMenuItemLight.IsEnabled = false;

            ApplicationBarMenuItem appBarMenuItem2 = new ApplicationBarMenuItem() { Text = "固定至桌面" };
            appBarMenuItem2.Click += delegate(object sender, EventArgs e)
            {
                BookReader_ForBeginMenu();
            };
            ApplicationBarMenuItem appBarMenuItem3 = new ApplicationBarMenuItem() { Text = "目录/书签" };
            appBarMenuItem3.Click += delegate(object sender, EventArgs e)
            {
                BookReader_BookChapterMenu();
            };
            ApplicationBarMenuItem appBarMenuItem4 = new ApplicationBarMenuItem() { Text = "添加书签" };
            appBarMenuItem4.Click += delegate(object sender, EventArgs e)
            {
                BookReader_AddMarkerMenu();
            };
            ApplicationBarMenuItem appBarMenuItem5 = new ApplicationBarMenuItem() { Text = "复制本页内容" };
            appBarMenuItem5.Click += delegate(object sender, EventArgs e)
            {
                this.BookReader_CopyContent();
            };
            //


            ApplicationBar.MenuItems.Add(appBarMenuItemDark);
            ApplicationBar.MenuItems.Add(appBarMenuItemLight);
            //ApplicationBar.MenuItems.Add(appBarMenuItem1);
            ApplicationBar.MenuItems.Add(appBarMenuItem2);
            ApplicationBar.MenuItems.Add(appBarMenuItem3);
            ApplicationBar.MenuItems.Add(appBarMenuItem4);
            //ApplicationBar.MenuItems.Add(appBarMenuItem5);
        }




        #endregion 菜单设置

        #region 进度时间显示
        private void ShowTimeProcessStatusbar()
        {
            Binding bindingReaderPage_Percentage = new Binding()
            {
                Mode = BindingMode.TwoWay,
                Source = this.rppc,
                Path = new PropertyPath("ReaderPage_Percentage", new object[0])
            };
            this.percentageText.Margin = new Thickness(10, 0, 0, 0);
            this.percentageText.HorizontalAlignment = HorizontalAlignment.Left;
            this.percentageText.VerticalAlignment = VerticalAlignment.Bottom;
            this.percentageText.SetBinding(TextBlock.TextProperty, bindingReaderPage_Percentage);
            this.percentageText.Visibility = System.Windows.Visibility.Visible;
            //this.LayoutRoot.Children.Add(this.percentageText);
            //
            Binding bindingReaderPage_Time = new Binding()
            {
                Mode = BindingMode.TwoWay,
                Source = this.rptc,
                Path = new PropertyPath("ReaderPage_Time", new object[0])
            };
            this.timeText.Margin = new Thickness(0, 0, 10, 0);
            this.timeText.HorizontalAlignment = HorizontalAlignment.Right;
            this.timeText.VerticalAlignment = VerticalAlignment.Bottom;
            this.timeText.SetBinding(TextBlock.TextProperty, bindingReaderPage_Time);
            this.rptc.ReaderPage_Time = GetNowTime.Get();
            this.timeText.Visibility = System.Windows.Visibility.Visible;
            //this.LayoutRoot.Children.Add(this.timeText);
            //
            this.txtAdClickInfo.Text = "可以的话麻烦点击一下广告支持我！";
            this.txtAdClickInfo.FontSize = 18;
            this.txtAdClickInfo.HorizontalAlignment = HorizontalAlignment.Center;
            this.txtAdClickInfo.VerticalAlignment = VerticalAlignment.Bottom;
            //
            #region 提示和广告
            Grid grid = new Grid();
            //grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(20) });
            //grid.RowDefinitions.Add(new RowDefinition());
            grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(15, GridUnitType.Star) });
            grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(70, GridUnitType.Star) });
            grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(15, GridUnitType.Star) });
            Grid.SetRow(this.percentageText, 0);
            Grid.SetColumn(this.percentageText, 0);
            Grid.SetRow(this.timeText, 0);
            Grid.SetColumn(this.timeText, 2);
            Grid.SetRow(txtAdClickInfo, 0);
            Grid.SetColumn(txtAdClickInfo, 1);
            grid.Children.Add(this.percentageText);
            grid.Children.Add(this.txtAdClickInfo);
            grid.Children.Add(this.timeText);
            grid.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
            grid.Background = new SolidColorBrush(Colors.Transparent);
            grid.Height = 100 - 80;
            grid.Width = 480;
            this.LayoutRoot.Children.Add(grid);
            //加载广告            
            this.popupAd.Height = 80;
            this.popupAd.Width = 480;
            //广告位高度80，ApplicationBar有23
            this.popupAd.VerticalOffset = Application.Current.Host.Content.ActualHeight - 80 - 30;
            this.popupAd.HorizontalOffset = 0;
            this.sufaceAdControl = new SurfaceAdControl()
            {
                AdPosition = adPosition,
                AdToken = adToken,
                AdRefreshInterval = 5,
                IsShowCloseIcon = true
            };
            this.sufaceAdControl.OnApplicationAuthEvent += ad_OnApplicationAuthEvent;
            this.sufaceAdControl.OnAdRequest += ad_OnAdRequest;
            this.sufaceAdControl.OnAdRequestFailed += ad_OnAdRequestFailed;
            this.sufaceAdControl.OnAdRequestLoaded += ad_OnAdRequestLoaded;
            this.sufaceAdControl.OnShowAdScreen += ad_OnShowAdScreen;
            this.sufaceAdControl.OnDismissAdScreen += ad_OnDismissAdScreen;
            this.sufaceAdControl.OnCloseAd += ad_OnCloseAd;
            this.sufaceAdControl.InitAdControl(AdModeType.Normal);
            this.popupAd.Child = this.sufaceAdControl;
            this.popupAd.IsOpen = true;
            #endregion  提示和广告
        }
        #endregion  进度时间显示

        public BookReaderPage()
        {
            this.InitializeComponent();
            ShowTimeProcessStatusbar();
            BuildLocalizedApplicationBar();

            Binding binding2 = new Binding()
            {
                Mode = BindingMode.TwoWay,
                Source = this.rpbc,
                Path = new PropertyPath("ReaderPage_Bright", new object[0])
            };
            Grid grid = new Grid()
            {
                Margin = new Thickness(0, 0, 0, 0),
                Background = new SolidColorBrush(Color.FromArgb(255, 0, 0, 0))
            };
            grid.SetBinding(UIElement.OpacityProperty, binding2);
            this.LayoutRoot.Children.Add(grid);
            App.ReaderPage_Night = (bool)SettingHelper.GetValueFromSettings("BookReader_NightMode");
            if (!App.ReaderPage_Night)
            {
                this.rpbc.ReaderPage_Bright = (double)SettingHelper.GetValueFromSettings("ReaderPage_Bright");
            }
            else
            {
                this.rpbc.ReaderPage_Bright = (double)SettingHelper.GetValueFromSettings("ReaderPage_NightBright");
            }
            this.BookReader_BackgroundNum = (int)SettingHelper.GetValueFromSettings("BookReader_BackgroundNum");
            this.fontSize = (int)SettingHelper.GetValueFromSettings("BookReader_fontSize");
            this.pageTurnStoryboard = base.Resources["pageTurnStoryboard"] as Storyboard;
            this.previousPageCanvasIndex = 0;
            this.currentPageCanvasIndex = 1;
            this.nextPageCanvasIndex = 2;
            this.RemapCanvasPointers();
            this.BookReader_BackgroundMenu(this.BookReader_BackgroundNum);
            base.BackKeyPress += (this.OnBackKeyPress);
            base.ManipulationStarted += (this.BookReader_ManipulationStarted);
            base.ManipulationDelta += (this.BookReader_ManipulationDelta);
            base.ManipulationCompleted += (this.BookReader_ManipulationCompleted);
        }


        public void OnBackKeyPress(object sender, CancelEventArgs e)
        {
            if (SettingHelper.IsSettings("ReaderPageBack"))
            {
                SettingHelper.DeleteSettings("ReaderPageBack");
                base.NavigationService.GoBack();
                return;
            }
            NaviService.Navigate(QQReaderPage.EMainPage, "");
            e.Cancel = true;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            this.BookReader_SaveSetting();
            this.rpTopControl = null;
            this.rpBottomControl = null;
            ShellTile shellTile = ShellTile.ActiveTiles.FirstOrDefault<ShellTile>((ShellTile x) => x.NavigationUri.ToString().Contains(App.ReaderFileName));
            if (shellTile != null)
            {
                BookList_M currentBook = this.GetCurrentBook();
                StandardTileData standardTileDatum = new StandardTileData();
                Uri converUri = new Uri(currentBook.str_Cover_M, UriKind.RelativeOrAbsolute);
                char[] chrArray = new char[] { '/' };
                string str = string.Concat("/Shared/ShellContent/", converUri.ToString().TrimStart(chrArray).Replace('/', '_'));
                if (GetNowTime.Isostore(str))
                {
                    standardTileDatum.BackgroundImage = (new Uri(string.Concat("isostore:", str)));
                }
                else if (!InternalBook.IsInternalBook(currentBook.str_Id_M))
                {
                    standardTileDatum.BackgroundImage = (new Uri("/Resource/DefaultBookBackground.jpg", UriKind.Relative));
                }
                else
                {
                    standardTileDatum.BackgroundImage = (new Uri(currentBook.str_Cover_M, UriKind.Relative));
                }
                standardTileDatum.BackTitle = (GetNowTime.SetPercentageText(this.BookReader_Percentage));
                standardTileDatum.BackContent = (currentBook.str_Title_M);
                shellTile.Update(standardTileDatum);
            }
            this.UpdateTime.Stop();
            //
            if (this.popupReaderConfig != null)
            {
                this.popupReaderConfig.IsOpen = false;
                this.popupReaderConfig = null;
            }
            this.sufaceAdControl.RemoveSurfaceAdControl();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            App.QQReader_prePageId = App.QQReader_pageId;
            App.QQReader_pageId = "QQReader_ReaderPage";
            if (!SettingHelper.IsSettings("ReaderPageHelp"))
            {
                SettingHelper.SaveInToSettings("ReaderPageHelp", true);
                this.rph = new ReaderPageHelp(this);
                this.LayoutRoot.Children.Add(this.rph);
            }
            if (this.tp == null)
            {
                App.ReaderFileName = base.NavigationContext.QueryString["FileName"];
                this.tp = new Typesetting(App.ReaderFileName);
            }
            if (!SettingHelper.IsSettings(string.Concat(App.ReaderFileName, "CurrentReaderBook")))
            {
                this.lbpl_m.int_ReaderIndex_M = 0;
                this.lbpl_m.double_ReaderProgress_M = 0;
                SettingHelper.SaveInToSettings(string.Concat(App.ReaderFileName, "CurrentReaderBook"), this.lbpl_m);
            }
            else
            {
                this.lbpl_m = SettingHelper.GetValueFromSettings(string.Concat(App.ReaderFileName, "CurrentReaderBook")) as LocalBookProgressList_M;
                this.currentPageIndex = this.lbpl_m.int_ReaderIndex_M;
            }
            if (this.drawPage == null)
            {
                this.drawPage = new pageInfo();
            }
            if (this.rpTopControl == null)
            {
                this.rpTopControl = new ReaderPageTopControl();
            }
            if (this.rpBottomControl == null)
            {
                this.rpBottomControl = new ReaderPageBottomControl();
            }
            this.UpdateTime.Tick += new EventHandler((object s, EventArgs ex) => this.rptc.ReaderPage_Time = string.Concat("   ", GetNowTime.Get()));
            this.UpdateTime.Start();
            this.UpdateTime.Interval = TimeSpan.FromMilliseconds(1000);
            this.initPage = 0;
            this.loaded = true;
            this.BookReader_InitPage();
        }


        public void BookReader_AddMarkerMenu()
        {
            List<BookMarkerList_M> bookMarkerListMs;
            bookMarkerListMs = (!SettingHelper.IsSettings(string.Concat(App.ReaderFileName, "markerList")) ? new List<BookMarkerList_M>() : new List<BookMarkerList_M>((List<BookMarkerList_M>)SettingHelper.GetValueFromSettings(string.Concat(App.ReaderFileName, "markerList"))));
            BookMarkerList_M bookMarkerListM = new BookMarkerList_M()
            {
                MarkerList_Title = string.Concat("位于本书的", GetNowTime.SetPercentageText(this.BookReader_Percentage), "处"),
                MarkerList_Date = DateTime.Now.ToString()
            };
            int num = (Typesetting.getBookBuf().Length - this.currentPageIndex <= 40 ? Typesetting.getBookBuf().Length - this.currentPageIndex - 1 : 40);
            char[] chrArray = new char[num];
            Typesetting.getBookBuf().CopyTo(this.currentPageIndex, chrArray, 0, num);
            bookMarkerListM.MarkerList_PreviewString = (new string(chrArray)).Replace('\n', ' ');
            bookMarkerListM.MarkerList_Index = this.currentPageIndex;
            for (int i = 0; i < bookMarkerListMs.Count; i++)
            {
                if (bookMarkerListM.MarkerList_Index == bookMarkerListMs[i].MarkerList_Index)
                {
                    Prompt.PromptMessage("提示：书签添加成功！");
                    return;
                }
            }
            bookMarkerListMs.Insert(0, bookMarkerListM);
            SettingHelper.SaveInToSettings(string.Concat(App.ReaderFileName, "markerList"), bookMarkerListMs);
            Prompt.PromptMessage("提示：书签添加成功！");
        }

        public void BookReader_BackgroundMenu(int num)
        {
            SolidColorBrush solidColorBrush;
            this.BookReader_BackgroundNum = num;
            SettingHelper.SaveInToSettings("BookReader_BackgroundNum", this.BookReader_BackgroundNum);
            App.ReaderPage_Night = (bool)SettingHelper.GetValueFromSettings("BookReader_NightMode");
            ImageBrush imageBrush = new ImageBrush();
            if (App.ReaderPage_Night)
            {
                imageBrush.ImageSource = new BitmapImage(new Uri("/Resource/black.jpg", UriKind.Relative));
                solidColorBrush = new SolidColorBrush(Color.FromArgb(255, 200, 200, 200));
            }
            else
            {
                switch (this.BookReader_BackgroundNum)
                {
                    case 0:
                        {
                            imageBrush.ImageSource = new BitmapImage(new Uri("/Resource/yellow.jpg", UriKind.Relative));
                            solidColorBrush = new SolidColorBrush(Color.FromArgb(255, 67, 46, 12));
                            break;
                        }
                    case 1:
                        {
                            imageBrush.ImageSource = new BitmapImage(new Uri("/Resource/white.jpg", UriKind.Relative));
                            solidColorBrush = new SolidColorBrush(Color.FromArgb(255, 17, 30, 2));
                            break;
                        }
                    case 2:
                        {
                            imageBrush.ImageSource = new BitmapImage(new Uri("/Resource/blue.jpg", UriKind.Relative));
                            solidColorBrush = new SolidColorBrush(Color.FromArgb(255, 233, 240, 246));
                            break;
                        }
                    default:
                        {
                            imageBrush.ImageSource = new BitmapImage(new Uri("/Resource/pink.jpg", UriKind.Relative));
                            solidColorBrush = new SolidColorBrush(Color.FromArgb(255, 150, 56, 84));
                            break;
                        }
                }
            }
            Binding binding = new Binding()
            {
                Mode = BindingMode.TwoWay,
                Source = this.rpbgc,
                Path = new PropertyPath("ReaderPage_Background", new object[0])
            };
            this.previousCanvas.ClearValue(Panel.BackgroundProperty);
            this.currentCanvas.ClearValue(Panel.BackgroundProperty);
            this.nextCanvas.ClearValue(Panel.BackgroundProperty);
            this.previousCanvas.SetBinding(Panel.BackgroundProperty, binding);
            this.currentCanvas.SetBinding(Panel.BackgroundProperty, binding);
            this.nextCanvas.SetBinding(Panel.BackgroundProperty, binding);
            this.rpbgc.ReaderPage_Background = imageBrush;
            this.control.Foreground = solidColorBrush;
        }

        public void BookReader_BookChapterMenu()
        {
            NaviService.Navigate(QQReaderPage.EBookChapterPage, "");
        }

        public void BookReader_BrightMenu(double num)
        {
            this.rpbc.ReaderPage_Bright = num;
            if (App.ReaderPage_Night)
            {
                SettingHelper.SaveInToSettings("ReaderPage_NightBright", this.rpbc.ReaderPage_Bright);
                return;
            }
            SettingHelper.SaveInToSettings("ReaderPage_Bright", this.rpbc.ReaderPage_Bright);
        }

        public void BookReader_FontMenu(int num)
        {
            this.fontSize = num;
            this.initPage = 0;
            SettingHelper.SaveInToSettings("BookReader_fontSize", this.fontSize);
            this.BookReader_InitPage();
        }

        public void BookReader_ForBeginMenu()
        {
            try
            {
                ShellTile shellTile = ShellTile.ActiveTiles.FirstOrDefault<ShellTile>((ShellTile x) => x.NavigationUri.ToString().Contains(App.ReaderFileName));
                BookList_M currentBook = this.GetCurrentBook();

                StandardTileData standardTileDatum = new StandardTileData();
                Uri converUri = new Uri(currentBook.str_Cover_M, UriKind.RelativeOrAbsolute);
                //string absolutePath = converUri.AbsolutePath;

                char[] chrArray = new char[] { '/' };
                //string str = string.Concat("/Shared/ShellContent/", absolutePath.TrimStart(chrArray).Replace('/', '_'));
                string str = string.Concat("/Shared/ShellContent/", converUri.ToString().TrimStart(chrArray).Replace('/', '_'));
                if (GetNowTime.Isostore(str))
                {
                    standardTileDatum.BackgroundImage = (new Uri(string.Concat("isostore:", str)));
                }
                else if (!InternalBook.IsInternalBook(currentBook.str_Id_M))
                {
                    standardTileDatum.BackgroundImage = (new Uri("/Resource/DefaultBookBackground.jpg", UriKind.Relative));
                }
                else
                {
                    standardTileDatum.BackgroundImage = (new Uri(currentBook.str_Cover_M, UriKind.Relative));
                }
                standardTileDatum.BackBackgroundImage = (new Uri("/Resource/backImage.jpg", UriKind.Relative));
                standardTileDatum.BackTitle = (GetNowTime.SetPercentageText(this.BookReader_Percentage));
                standardTileDatum.BackContent = (currentBook.str_Title_M);
                if (shellTile != null)
                {
                    shellTile.Delete();
                    return;
                }
                if (SettingHelper.IsSettings("ReaderPageBack"))
                {
                    SettingHelper.DeleteSettings("ReaderPageBack");
                }
                ShellTile.Create(new Uri(string.Concat("/Pages/BookReaderPage.xaml?FileName=", App.ReaderFileName), UriKind.Relative), standardTileDatum);
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
            }
        }

        public void BookReader_InitPage()
        {
            this.RenderPage(PageDisplacement.Current);
            BookReaderPage bookReaderPage1 = this;
            bookReaderPage1.initPage = bookReaderPage1.initPage + 1;
            (new Thread(() => Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                this.RenderPage(PageDisplacement.Previous);
                BookReaderPage bookReaderPage = this;
                bookReaderPage.initPage = bookReaderPage.initPage + 1;
            }))).Start();
            (new Thread(() => Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                this.RenderPage(PageDisplacement.Next);
                BookReaderPage bookReaderPage = this;
                bookReaderPage.initPage = bookReaderPage.initPage + 1;
            }))).Start();
        }

        private void BookReader_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
        {
            e.Handled = true;
            if (this.pageTurnStoryboard.GetCurrentState() != ClockState.Active)
            {
                FrameworkElement originalSource = e.OriginalSource as FrameworkElement;
                Point point = e.ManipulationContainer.TransformToVisual(this).Transform(e.ManipulationOrigin);
                if (this.currentPageIndex <= 0 && (e.TotalManipulation.Translation.X > 0 || e.TotalManipulation.Translation.X == 0 && point.X < 160 || point.Y < 160 && point.X < 320))
                {
                    Prompt.PromptMessage("提示：已至本书首页");
                    return;
                }
                if (this.currentPageIndex + this.currentPageCount >= this.tp.getBookLength() && (e.TotalManipulation.Translation.X < 0 || e.TotalManipulation.Translation.X == 0 && point.X >= 320 || point.Y > 640 && point.X > 160))
                {
                    Prompt.PromptMessage("提示：已至本书尾页");
                    return;
                }
                this.OnTouchFlick(originalSource, point, e.TotalManipulation.Translation.X);
            }
        }

        private void BookReader_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
        {
            e.Handled = true;
            object originalSource = e.OriginalSource;
            e.ManipulationContainer.TransformToVisual(this).Transform(e.ManipulationOrigin);
            if (this.currentPageIndex <= 0 && e.DeltaManipulation.Translation.X > 0 || this.currentPageIndex + this.currentPageCount >= this.tp.getBookLength() && e.DeltaManipulation.Translation.X < 0)
            {
                return;
            }
            this.OnTouchDrag(e.DeltaManipulation.Translation.X);
        }

        private void BookReader_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
        {
            e.Handled = true;
            if (this.pageTurnStoryboard.GetCurrentState() == ClockState.Active)
            {
                e.Complete();
                return;
            }
            object originalSource = e.OriginalSource;
            e.ManipulationContainer.TransformToVisual(this).Transform(e.ManipulationOrigin);
        }

        public void BookReader_NightMenu()
        {
            App.ReaderPage_Night = (bool)SettingHelper.GetValueFromSettings("BookReader_NightMode");
            if (!App.ReaderPage_Night)
            {
                this.rpbc.ReaderPage_Bright = (double)SettingHelper.GetValueFromSettings("ReaderPage_Bright");
            }
            else
            {
                this.rpbc.ReaderPage_Bright = (double)SettingHelper.GetValueFromSettings("ReaderPage_NightBright");
            }
            this.BookReader_BackgroundMenu(this.BookReader_BackgroundNum);
        }

        public void BookReader_ProgressMenu(float progress)
        {
            this.BookReader_Percentage = (double)progress * 0.01;
            if (this.BookReader_Percentage < 1)
            {
                this.currentPageIndex = (int)((double)this.tp.getBookLength() * this.BookReader_Percentage);
            }
            else
            {
                this.currentPageIndex = this.tp.getBookLength() - 8;
            }
            this.lbpl_m.double_ReaderProgress_M = this.BookReader_Percentage;
            SettingHelper.SaveInToSettings(string.Concat(App.ReaderFileName, "CurrentReaderBook"), this.lbpl_m);
            this.initPage = 0;
            this.BookReader_InitPage();
        }

        public void BookReader_SaveSetting()
        {
            SettingHelper.SaveInToSettings("BookReader_fontSize", this.fontSize);
            SettingHelper.SaveInToSettings("BookReader_BackgroundNum", this.BookReader_BackgroundNum);
            SettingHelper.SaveInToSettings("ReaderPage_Bright", this.rpbc.ReaderPage_Bright);
            this.lbpl_m.int_ReaderIndex_M = this.currentPageIndex;
            this.lbpl_m.double_ReaderProgress_M = this.BookReader_Percentage;
            SettingHelper.SaveInToSettings(string.Concat(App.ReaderFileName, "CurrentReaderBook"), this.lbpl_m);
        }

        public void BottomTextCollapsed()
        {
            //this.menuText.Visibility = Visibility.Collapsed;
            //this.menuTextResponse.Visibility = Visibility.Collapsed;
            //this.percentageText.Visibility = Visibility.Collapsed;
            //this.timeText.Visibility = Visibility.Collapsed;
            this.menuText.Text = "Thanks";
        }

        public void BottomTextVisible()
        {
            //this.menuText.Visibility = Visibility.Visible;
            // this.menuTextResponse.Visibility = Visibility.Visible;
            //this.percentageText.Visibility = Visibility.Visible;
            //this.timeText.Visibility = Visibility.Visible;
            this.menuText.Text = "Click Ad";
        }

        private int DecrementCanvasIndex(int index)
        {
            if (index <= 0)
            {
                return 2;
            }
            int num = index - 1;
            index = num;
            return num;
        }

        private void DoRenderPage(Canvas canvas, PageDisplacement displacement)
        {           

            if (this.graphics == null)
            {
                this.graphics = new GraphicsExtendedImpl();
            }
            this.graphics.FrameBuffer = canvas;
            this.graphics.BeginBatchDrawing();
            switch (displacement)
            {
                case PageDisplacement.Current:
                    {
                        this.readerIndex = this.currentPageIndex;
                        break;
                    }
                case PageDisplacement.Previous:
                    {
                        this.readerIndex = this.previousPageIndex;
                        break;
                    }
                case PageDisplacement.Next:
                    {
                        this.readerIndex = this.nextPageIndex + this.nextPageCount;
                        break;
                    }
            }
            this.RemovePage();
            this.tp.Calculate(this.drawPage, this.readerIndex, this.fontSize, displacement);
            if (this.initPage < 3)
            {
                switch (displacement)
                {
                    case PageDisplacement.Current:
                        {
                            this.previousPageIndex = this.drawPage.textIndex;
                            this.currentPageIndex = this.drawPage.textIndex;
                            this.nextPageIndex = this.drawPage.textIndex;
                            this.currentPageCount = this.drawPage.textCount;
                            this.nextPageCount = this.drawPage.textCount;
                            break;
                        }
                    case PageDisplacement.Previous:
                        {
                            this.previousPageIndex = this.drawPage.textIndex;
                            this.previousPageCount = this.drawPage.textCount;
                            break;
                        }
                    case PageDisplacement.Next:
                        {
                            this.nextPageIndex = this.drawPage.textIndex;
                            this.nextPageCount = this.drawPage.textCount;
                            break;
                        }
                }
            }
            else
            {
                switch (displacement)
                {
                    case PageDisplacement.Previous:
                        {
                            this.nextPageIndex = this.currentPageIndex;
                            this.nextPageCount = this.currentPageCount;
                            this.currentPageIndex = this.previousPageIndex;
                            this.currentPageCount = this.previousPageCount;
                            this.previousPageIndex = this.drawPage.textIndex;
                            this.previousPageCount = this.drawPage.textCount;
                            break;
                        }
                    case PageDisplacement.Next:
                        {
                            this.previousPageIndex = this.currentPageIndex;
                            this.previousPageCount = this.currentPageCount;
                            this.currentPageIndex = this.nextPageIndex;
                            this.currentPageCount = this.nextPageCount;
                            this.nextPageIndex = this.drawPage.textIndex;
                            this.nextPageCount = this.drawPage.textCount;
                            break;
                        }
                }
            }
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(displacement.ToString ());
            for (int i = 0; i < this.drawPage.textContent.Count; i++)
            {
                UIElementCollection children = this.graphics.FrameBuffer.Children;
                TextBlock textBlock = new TextBlock()
                {
                    Text = this.drawPage.textContent[i],
                    FontSize = (double)this.fontSize,
                    Margin = new Thickness((double)this.drawPage.textContentX[i], (double)this.drawPage.textContentY[i], 0, 0)
                };
                //System.Diagnostics.Debug.WriteLine("------" + textBlock.Text + "\t" + textBlock.Margin.ToString());
                ((PresentationFrameworkCollection<UIElement>)children).Add(textBlock);
                sb.Append(this.drawPage.textContent[i]);
            }
            this.BookReader_Percentage = (double)this.currentPageIndex / (double)this.tp.getBookLength();
            this.rppc.ReaderPage_Percentage = GetNowTime.SetPercentageText(this.BookReader_Percentage);
            this.graphics.EndBatchDrawing();

            LogHelper.LogInfo(sb.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        public BookList_M GetCurrentBook()
        {
            //BookList_M bookListM = new BookList_M();
            //foreach (BookList_M bookListM1 in App.LocalBook.T_LocalBookList_VM1())
            //{
            //    if (bookListM1.str_Id_M != App.ReaderFileName)
            //    {
            //        continue;
            //    }
            //    bookListM = bookListM1;
            //    break;
            //}
            //if (bookListM.str_Id_M != App.ReaderFileName)
            //{
            //    foreach (BookList_M bookListM2 in App.LocalBook.T_LocalBookList_VM2())
            //    {
            //        if (bookListM2.str_Id_M != App.ReaderFileName)
            //        {
            //            continue;
            //        }
            //        bookListM = bookListM2;
            //        break;
            //    }
            //}
            //return bookListM;
            BookList_M bookListM = new BookList_M();
            foreach (BookList_M bookListM1 in App.LocalBook.T_LocalBookListViewModel())
            {
                if (bookListM1.str_Id_M != App.ReaderFileName)
                {
                    continue;
                }
                bookListM = bookListM1;
                break;
            }
            return bookListM;
        }

        private void GoToPage(PageDisplacement displacement)
        {
            if (this.loaded)
            {
                if (displacement == PageDisplacement.Previous || displacement == PageDisplacement.Next)
                {
                    int num = (displacement == PageDisplacement.Next ? -(int)this.LayoutRoot.ActualWidth : (int)this.LayoutRoot.ActualWidth);
                    double x = ((TranslateTransform)this.currentCanvas.RenderTransform).X;
                    this.MoveCurrentPage(x, (double)num);
                    return;
                }
                if (displacement == PageDisplacement.Current)
                {
                    this.RenderPage(PageDisplacement.Current);
                }
            }
        }

        private int IncrementCanvasIndex(int index)
        {
            if (index >= 2)
            {
                return 0;
            }
            int num = index + 1;
            index = num;
            return num;
        }



        private void MenuBackground_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
        {
        }

        private void MenuBright_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
        {
        }

        private void MenuFontFamily_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
        {
        }

        private void MenuProgress_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
        {
        }

        private void menuTextResponse_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
        {
            e.Handled = true;
        }

        private void menuTextResponse_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
        {
            e.Complete();
            e.Handled = true;
        }

        private void menuTextResponse_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
        {
            e.Complete();
            e.Handled = true;
        }

        private void menuTextResponse_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            e.Handled = true;
            this.lbpl_m.double_ReaderProgress_M = this.BookReader_Percentage;
            SettingHelper.SaveInToSettings(string.Concat(App.ReaderFileName, "CurrentReaderBook"), this.lbpl_m);
            this.BottomTextCollapsed();
            this.pcc.ShowTopBottom(this, this.rpTopControl, this.rpBottomControl);
        }

        private void MoveCurrentPage(double from, double to)
        {
            if (this.pageTurnStoryboard.GetCurrentState() != ClockState.Active)
            {
                int actualWidth = (int)this.LayoutRoot.ActualWidth;
                DoubleAnimation item = (DoubleAnimation)this.pageTurnStoryboard.Children[this.previousPageCanvasIndex];
                DoubleAnimation nullable = (DoubleAnimation)this.pageTurnStoryboard.Children[this.currentPageCanvasIndex];
                DoubleAnimation doubleAnimation = (DoubleAnimation)this.pageTurnStoryboard.Children[this.nextPageCanvasIndex];
                nullable.From = new double?(from);
                nullable.To = new double?(to);
                bool flag = false;
                if (to <= (double)(-actualWidth) || to >= (double)actualWidth)
                {
                    flag = true;
                }
                if (from > to)
                {
                    if (!flag)
                    {
                        item.From = new double?(from - (double)actualWidth);
                        item.To = new double?(to - (double)actualWidth);
                        doubleAnimation.From = new double?((double)actualWidth);
                        doubleAnimation.To = new double?((double)actualWidth);
                    }
                    else
                    {
                        this.previousCanvas.Visibility = Visibility.Collapsed;
                        doubleAnimation.From = new double?(from + (double)actualWidth);
                        doubleAnimation.To = new double?(to + (double)actualWidth);
                    }
                }
                else if (!flag)
                {
                    doubleAnimation.From = new double?(from + (double)actualWidth);
                    doubleAnimation.To = new double?(to + (double)actualWidth);
                    item.From = new double?((double)(-actualWidth));
                    item.To = new double?((double)(-actualWidth));
                }
                else
                {
                    this.nextCanvas.Visibility = Visibility.Collapsed;
                    item.From = new double?(from - (double)actualWidth);
                    item.To = new double?(to - (double)actualWidth);
                }
                this.pageTurnStoryboard.Completed += new EventHandler(this.OnPageTurnAnimationCompleted);
                this.pageTurnStoryboard.Begin();
            }
        }



        private void OnPageTurnAnimationCompleted(object sender, EventArgs e)
        {
            this.pageTurnStoryboard.Completed -= new EventHandler(this.OnPageTurnAnimationCompleted);
            GraphicsExtendedImpl.RemoveInvertGraphics(this.currentCanvas);
            PageDisplacement pageDisplacement = PageDisplacement.Current;
            if (this.previousCanvas.Visibility == Visibility.Collapsed)
            {
                this.previousPageCanvasIndex = this.IncrementCanvasIndex(this.previousPageCanvasIndex);
                this.currentPageCanvasIndex = this.IncrementCanvasIndex(this.currentPageCanvasIndex);
                this.nextPageCanvasIndex = this.IncrementCanvasIndex(this.nextPageCanvasIndex);
                pageDisplacement = PageDisplacement.Next;
            }
            else if (this.nextCanvas.Visibility == Visibility.Collapsed)
            {
                this.previousPageCanvasIndex = this.DecrementCanvasIndex(this.previousPageCanvasIndex);
                this.currentPageCanvasIndex = this.DecrementCanvasIndex(this.currentPageCanvasIndex);
                this.nextPageCanvasIndex = this.DecrementCanvasIndex(this.nextPageCanvasIndex);
                pageDisplacement = PageDisplacement.Previous;
            }
            this.RemapCanvasPointers();
            base.Dispatcher.BeginInvoke(() => this.RenderPage(pageDisplacement));
        }

        private void OnTouchDrag(double xDelta)
        {
            TranslateTransform renderTransform = this.previousCanvas.RenderTransform as TranslateTransform;
            renderTransform.X = renderTransform.X + xDelta;
            TranslateTransform x = this.currentCanvas.RenderTransform as TranslateTransform;
            x.X = x.X + xDelta;
            TranslateTransform translateTransform = this.nextCanvas.RenderTransform as TranslateTransform;
            translateTransform.X = translateTransform.X + xDelta;
        }

        private void OnTouchFlick(FrameworkElement touchTarget, Point position, double xTotal)
        {
            double num = xTotal;
            if (num < 0)
            {
                this.GoToPage(PageDisplacement.Next);
                return;
            }
            if (num > 0)
            {
                this.GoToPage(PageDisplacement.Previous);
                return;
            }
            if (position.X < 160 || position.Y < 160 && position.X < 320)
            {
                this.GoToPage(PageDisplacement.Previous);
                return;
            }
            if (position.X > 320 || position.Y > 640 && position.X > 160)
            {
                this.GoToPage(PageDisplacement.Next);
                return;
            }
            //this.lbpl_m.double_ReaderProgress_M = this.BookReader_Percentage;
            //SettingHelper.SaveInToSettings(string.Concat(App.ReaderFileName, "CurrentReaderBook"), this.lbpl_m);
            //this.BottomTextCollapsed();
            //this.pcc.ShowTopBottom(this, this.rpTopControl, this.rpBottomControl);
            if (this.popupReaderConfig != null)
            {
                this.popupReaderConfig.IsOpen = false;
                this.popupReaderConfig = null;
            }
        }

        private void RemapCanvasPointers()
        {
            int num = (int)((this.LayoutRoot.ActualWidth == 0 ? 480 : this.LayoutRoot.ActualWidth));
            this.previousCanvas = (Canvas)this.LayoutRoot.Children[this.previousPageCanvasIndex];
            this.currentCanvas = (Canvas)this.LayoutRoot.Children[this.currentPageCanvasIndex];
            this.nextCanvas = (Canvas)this.LayoutRoot.Children[this.nextPageCanvasIndex];
            ((TranslateTransform)this.previousCanvas.RenderTransform).X = (double)(-num);
            ((TranslateTransform)this.currentCanvas.RenderTransform).X = 0;
            ((TranslateTransform)this.nextCanvas.RenderTransform).X = (double)num;
            this.previousCanvas.Visibility = Visibility.Visible;
            this.currentCanvas.Visibility = Visibility.Visible;
            this.nextCanvas.Visibility = Visibility.Visible;
            if (this.LayoutRoot.ActualWidth != 0 && this.LayoutRoot.ActualHeight != 0 && !this.canvasClipped)
            {
                RectangleGeometry rectangleGeometry = new RectangleGeometry()
                {
                    Rect = new Rect(0, 0, this.LayoutRoot.ActualWidth, this.LayoutRoot.ActualHeight)
                };
                this.previousCanvas.Clip = rectangleGeometry;
                RectangleGeometry rectangleGeometry1 = new RectangleGeometry()
                {
                    Rect = new Rect(0, 0, this.LayoutRoot.ActualWidth, this.LayoutRoot.ActualHeight)
                };
                this.currentCanvas.Clip = rectangleGeometry1;
                RectangleGeometry rectangleGeometry2 = new RectangleGeometry()
                {
                    Rect = new Rect(0, 0, this.LayoutRoot.ActualWidth, this.LayoutRoot.ActualHeight)
                };
                this.nextCanvas.Clip = rectangleGeometry2;
                this.canvasClipped = true;
            }
        }

        public void RemoveHelpPage()
        {
            if (this.LayoutRoot.Children.IndexOf(this.rph) >= 0)
            {
                this.LayoutRoot.Children.Remove(this.rph);
            }
        }

        public void RemovePage()
        {
            this.drawPage.textIndex = 0;
            this.drawPage.textCount = 0;
            this.drawPage.textContentX.Clear();
            this.drawPage.textContent.Clear();
            this.drawPage.textContentY.Clear();
        }

        private void RenderPage(PageDisplacement displacement)
        {
            if (this.currentPageIndex <= 0 && displacement == PageDisplacement.Previous || this.currentPageIndex + this.currentPageCount >= this.tp.getBookLength() && displacement == PageDisplacement.Next)
            {
                return;
            }
            Canvas canva = null;
            switch (displacement)
            {
                case PageDisplacement.Current:
                    {
                        canva = this.currentCanvas;                        
                        break;
                    }
                case PageDisplacement.Previous:
                    {
                        canva = this.previousCanvas;                       
                        break;
                    }
                case PageDisplacement.Next:
                    {
                        canva = this.nextCanvas;                        
                        break;
                    }
            }
            canva.Visibility = Visibility.Visible;
            if (canva.ActualHeight == 0 || canva.ActualWidth == 0)
            {
                canva.UpdateLayout();
            }
            this.DoRenderPage(canva, displacement);
        }



        //#region ********************BannerAd********************
        void ad_OnCloseAd(object sender, EventArgs e)
        {
            UmengSDK.UmengAnalytics.TrackEvent(string.Concat(adPosition, Keys.UmengTrackEvent._AdClose.ToString()));
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void ad_OnDismissAdScreen(object sender, EventArgs e)
        {
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void ad_OnShowAdScreen(object sender, EventArgs e)
        {
            UmengSDK.UmengAnalytics.TrackEvent(string.Concat(adPosition, Keys.UmengTrackEvent._AdShow.ToString()));
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
            RemovePopupAd();
        }

        void ad_OnApplicationAuthEvent(object sender, string message)
        {
            LogHelper.LogInfo(message.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
            RemovePopupAd();
        }

        void ad_OnAdRequestLoaded(object sender, EventArgs e)
        {
            UmengSDK.UmengAnalytics.TrackEvent(string.Concat(adPosition, Keys.UmengTrackEvent._AdLoaded.ToString()));
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void ad_OnAdRequestFailed(object sender, SurfaceAdEventArgs e)
        {
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
            RemovePopupAd();
        }

        void ad_OnAdRequest(object sender, EventArgs e)
        {
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void RemovePopupAd()
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                if (this.sufaceAdControl != null)
                {
                    this.sufaceAdControl.RemoveSurfaceAdControl();
                }
                if (this.popupAd != null)
                {
                    this.popupAd.IsOpen = false;
                    this.popupAd = null;
                }
            });
        }

        private void BookReader_CopyContent()
        {
            var c = this.drawPage.textContent;

            StringBuilder content = new StringBuilder();
            foreach (UIElement element in this.LayoutRoot.Children)
            {
                if (element == null)
                    continue;
                LogHelper.LogInfo(element.GetType().FullName, this.GetType(), MethodBase.GetCurrentMethod());
                if (element is Canvas)
                {
                    var canvas = element as Canvas;
                    if (canvas == null)
                        continue;
                    //if (!canvas.Name.Equals("CanvasTwo"))
                    //    continue;
                    if (!(canvas.Children != null && canvas.Children.Count > 0))
                        continue;

                    content = new StringBuilder();
                    foreach (var can in canvas.Children)
                    {
                        //LogHelper.LogInfo(can.GetType().FullName, this.GetType(), MethodBase.GetCurrentMethod());
                        if (can is TextBlock)
                        {
                            TextBlock txt = can as TextBlock;
                            if (txt != null)
                            {
                                content.Append(txt.Text.ToString());
                            }
                        }
                    }
                    LogHelper.LogInfo("canvas.Name=" + canvas.Name + "\t" + content.ToString());
                }
            }
            //if (!string.IsNullOrEmpty(content.ToString()))
            //{
            //    Clipboard.SetText(content.ToString());
            //    MessageBox.Show(content.ToString());
            //    Prompt.PromptMessage(string.Concat("提示：共有 ", content.ToString().Length.ToString(), " 个字符被复制！"));
            //}
        }
        //#endregion ********************BannerAd********************

    }
}